$(function(){
	  showCartDetails();
	  $('#btnPay').click(function(){
			window.location.href="InsertOrderByCartServlet";
		});
});

function reduce (bookId){
		
	if($("#"+bookId).val()>1){
		$.post("UpdateQuantityServlet",{service:2,bookId:bookId},function(data){
			showCartDetails();
		})
	}
}

function add(bookId,stock){
	
	if($("#"+bookId).val()<stock){
	
		$.post("UpdateQuantityServlet",{service:1,bookId:bookId},function(data){
		
			showCartDetails();
		})
	}
	else{
		alert('Stock is not enough!');
	}
}

function showCartDetails(){
	$("#cart_list").text("");
	$.post("QueryCartDetailServlet",function(data,status){
		var bookInfo=data;
		if (bookInfo!=""){
		$(bookInfo).each(function(index,elem){
			$("#cart_list").append("<tr> \
	<td> \
		<a href='#'><img src='"+elem.book.Picture+"' style='width:100px;height:154px;' alt='Product' /></a> \
	</td> \
	<td> \
		<a href='#'>"+elem.book.BookName+"</a> \
	</td> \
	<td> \
		<div class='prd-quantity' value='"+elem.quantity+"'> \
			<input value='-' class='btnReduce' onclick='reduce("+elem.book.BookId+")' type='button'> \
			<input name='quantity1' id='"+elem.book.BookId+"' value='"+elem.quantity+"' class='txtAty' type='text'> \
			<input value='+' class='btnAdd' onclick='add("+elem.book.BookId+","+elem.book.Stock+")' type='button'> \
		</div> \
	</td> \
	<td>$"+elem.book.Price+"</td> \
	<td>$"+elem.price+"</td> \
	<td> \
		<a href='#' onclick='deleteBook("+elem.book.BookId+")' style='text-align:center;'> \
			<i class='fa fa-trash' style='font-size:18px;'></i> \
		</a> \
	</td> \
</tr>");
		})
		}
		else{
			$("#content").append("<div id='empty'><img src='images/empty.png'></div>");
		}
		
	},"json");
}
function deleteBook(bookId){
	$.ajax({
		data: {"bookId": bookId},
		type:"post",
		url:"DeleteOneCartDetail",
		success:function(response){
			if(response==="success"){
				showCartDetails();
			}
			else{
				alert('Delete failed');
			}
		}
	});
}
function backToCustomer(){
	window.location.href="customer.jsp";
}